import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isUndefined from "lodash/isUndefined";

var _dec, _dec2, _dec3, _class;

/**
 * 租户切换
 */
import React, { PureComponent } from 'react';
import { Icon, Modal, Spin, Table } from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { Bind } from 'lodash-decorators';
import { getCurrentOrganizationId, getCurrentTenant } from "../../../utils/utils";
import formatterCollections from "../../../utils/intl/formatterCollections";
import intl from "../../../utils/intl";
import notification from "../../../utils/notification";
import { cleanMenuTabs } from "../../../utils/menuTab";
import RecordCheckbox from "./RecordCheckbox";
import style from "./index.less?modules";
/**
 * 租户切换 Tenant
 *
 * @extends {PureComponent} - React.PureComponent
 * @reactProps {!boolean} [modalVisible=false] - 是否显示选择租户的模态框
 * @reactProps {!string} [selectTenant=''] - 用户选择的租户名称
 * @reactProps {!array} [historyTenantList=[]] - 缓存用户选择的租户数据
 * @reactProps {!array} [tenantList=[]] - 租户列表数据
 * @reactProps {!number} [organizationId] - 当前登录用户的租户ID
 * @reactProps {!string} [tenantName] - 当前登录用户的租户名称
 * @returns React.element
 */

var DefaultTenantSelect = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), (_class = /*#__PURE__*/function (_PureComponent) {
  _inherits(DefaultTenantSelect, _PureComponent);

  var _super = _createSuper(DefaultTenantSelect);

  /**
   * constructor - constructor方法
   * 组件构造函数
   */
  function DefaultTenantSelect(props) {
    var _this;

    _classCallCheck(this, DefaultTenantSelect);

    _this = _super.call(this, props);
    _this.state = {
      modalVisible: false,
      tenantId: getCurrentOrganizationId(),
      selectTenant: (getCurrentTenant() || {}).tenantName || ''
    };
    return _this;
  }
  /**
   * @function showModal - 显示和隐藏租户切换模态框
   * @param {boolean} flag - 显示或隐藏标识
   */


  _createClass(DefaultTenantSelect, [{
    key: "showModal",
    value: function showModal(flag) {
      var dispatch = this.props.dispatch;

      if (flag) {
        dispatch({
          type: 'user/fetchTenantList'
        });
      }

      this.setState({
        modalVisible: flag
      });
    }
    /**
     * @function handleSelectTenant - 选择租户
     * @param {object} record - 选择的租户行数据
     * @param {string} record.tenantId - 租户ID
     * @param {string} record.tenantName - 租户名称
     * @param {string} record.tenantNum - 租户编码
     */

  }, {
    key: "handleSelectTenant",
    value: function handleSelectTenant(record) {
      var _this2 = this;

      var dispatch = this.props.dispatch;
      this.setState({
        // modalVisible: false,
        // 设置 loading
        updateTenantLoading: true,
        selectTenant: record.tenantName
      }); // TODO 历史记录只需要缓存历史 而不需要缓存当前租户
      // 设置当前租户ID缓存
      // const saveTenant = setSession('currentTenant', record);
      // 重新设置租户历史数据缓存
      // warn 清空 tabs 信息

      cleanMenuTabs(); // 切换租户成功后跳转首页，刷新页面

      dispatch(routerRedux.push({
        pathname: '/'
      })); // 缓存当前用户的租户

      dispatch({
        type: 'user/updateCurrentTenant',
        payload: {
          tenantId: record.tenantId
        }
      }).then(function (res) {
        if (res) {
          dispatch(routerRedux.push({
            pathname: '/workplace'
          })); // 成功 刷新页面

          window.location.reload();
        } else {
          // 失败 不关闭模态框
          _this2.setState({
            updateTenantLoading: false
          });
        }
      });
    }
    /**
     * 修改默认租户
     */

  }, {
    key: "handleChangeDefaultTenant",
    value: function handleChangeDefaultTenant(record) {
      // 如果已经设置了 默认租户 则 不能切换
      var payload = {};

      if (_isUndefined(record.defaultTenantId)) {
        payload.tenantId = record.tenantId;
      }

      var dispatch = this.props.dispatch;
      dispatch({
        type: 'user/updateDefaultTenant',
        payload: payload
      }).then(function (res) {
        if (res) {
          notification.success();
          dispatch({
            type: 'user/fetchTenantList'
          });
        }
      });
    }
  }, {
    key: "render",
    value: function render() {
      var _this3 = this;

      var _this$props = this.props,
          _this$props$tenantLis = _this$props.tenantList,
          tenantList = _this$props$tenantLis === void 0 ? [] : _this$props$tenantLis,
          tenantName = _this$props.tenantName,
          _this$props$allLoadin = _this$props.allLoading,
          allLoading = _this$props$allLoadin === void 0 ? false : _this$props$allLoadin;
      var _this$state = this.state,
          tenantId = _this$state.tenantId,
          _this$state$updateTen = _this$state.updateTenantLoading,
          updateTenantLoading = _this$state$updateTen === void 0 ? false : _this$state$updateTen;
      var columns = [{
        title: intl.get('entity.tenant.name').d('租户名称'),
        dataIndex: 'tenantName',
        render: function render(text, record) {
          return /*#__PURE__*/React.createElement("div", {
            className: style.tenant
          }, record.tenantId === tenantId && /*#__PURE__*/React.createElement("div", {
            className: style['tenant-select-wrapper']
          }), /*#__PURE__*/React.createElement("a", {
            onClick: function onClick() {
              return _this3.handleSelectTenant(record);
            }
          }, text, record.tenantId === tenantId && "(".concat(intl.get('cpaas.common.current').d('当前'), ")")));
        }
      }, {
        title: intl.get('entity.tenant.code').d('租户编码'),
        width: 100,
        dataIndex: 'tenantNum'
      }, {
        title: intl.get('cpaas.common.view.tenantSelect.defaultTenant').d('默认租户'),
        width: 90,
        dataIndex: 'defaultTenantId',
        render: function render(defaultTenantId, record) {
          return /*#__PURE__*/React.createElement(RecordCheckbox, {
            record: record,
            onClick: _this3.handleChangeDefaultTenant,
            checked: !_isUndefined(defaultTenantId)
          });
        }
      }];
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(React.Fragment, null, this.state.selectTenant ? /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("span", {
        style: {
          width: '100%',
          display: 'inline-block',
          marginRight: '12px',
          backgroundColor: 'rgba(255, 255, 255,.1)',
          color: '#666'
        },
        size: "small",
        onClick: function onClick() {
          return _this3.showModal(true);
        }
      }, this.state.selectTenant)) : tenantName ? /*#__PURE__*/React.createElement("span", {
        style: {
          width: '100%',
          display: 'inline-block',
          marginRight: '12px',
          backgroundColor: 'rgba(255, 255, 255,.1)'
        },
        size: "small",
        onClick: function onClick() {
          return _this3.showModal(true);
        }
      }, /*#__PURE__*/React.createElement(Icon, {
        type: "home"
      }), tenantName) : ''), /*#__PURE__*/React.createElement(Modal, {
        title: intl.get('cpaas.common.view.tenantSelect.title').d('选择租户'),
        width: "620px",
        bodyStyle: {
          paddingTop: 0,
          height: '460px',
          overflow: 'scroll'
        },
        visible: this.state.modalVisible,
        onCancel: function onCancel() {
          return _this3.showModal(false);
        },
        footer: null
      }, /*#__PURE__*/React.createElement(Spin, {
        spinning: updateTenantLoading
      }, /*#__PURE__*/React.createElement(Table, {
        bordered: true,
        style: {
          marginTop: 24
        },
        rowKey: "tenantId",
        pagination: false,
        loading: allLoading,
        dataSource: tenantList,
        columns: columns
      }))));
    }
  }]);

  return DefaultTenantSelect;
}(PureComponent), (_applyDecoratedDescriptor(_class.prototype, "showModal", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "showModal"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleSelectTenant", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "handleSelectTenant"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleChangeDefaultTenant", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "handleChangeDefaultTenant"), _class.prototype)), _class));
export default formatterCollections({
  code: ['cpfm.tenantSelect', 'entity.tenant']
})(connect(function (_ref) {
  var _ref$user = _ref.user;
  _ref$user = _ref$user === void 0 ? {} : _ref$user;
  var _ref$user$tenantList = _ref$user.tenantList,
      tenantList = _ref$user$tenantList === void 0 ? [] : _ref$user$tenantList,
      tenantName = _ref$user.currentUser.tenantName,
      loading = _ref.loading;
  return {
    tenantList: tenantList,
    tenantName: tenantName,
    allLoading: loading.effects['user/updateDefaultTenant'] || loading.effects['user/fetchTenantList']
  };
})(DefaultTenantSelect));